import mc
import re
import time
import traceback
import sys

mc.ActivateWindow(14000)

TV5_VIDEO_URL = "http://video.tv5.ca"
TV5_VIDEO_AZ = "a-z"

def getEmissionsAZ():
	emissions = []
	
	#mc.LogDebug("getEmissionsAZ: Debut")
	sg = mc.Http()
	html = sg.Get(TV5_VIDEO_URL + '/' + TV5_VIDEO_AZ)
	results = re.compile('a class="title_emission" href="(.+?)">(.+?)</a>').findall(html)

	emissions = mc.ListItems()

	for url, name in results:
		item = mc.ListItem(mc.ListItem.MEDIA_UNKNOWN)
		item.SetLabel(name)
		item.SetPath(url)
		item.SetProperty('flag','emissions') #FLAG
		emissions.append(item)
		
	mc.LogDebug("getEmissionsAZ: Fin!")
	
	return emissions
	

# Aller chercher la liste des episodes dans la page	
def getEpidodes(url):
	episodes = []
	
	sg = mc.Http()
	html = sg.Get(url)
	#results = re.compile('<a href="(.+?)"><img src="(.+?)" /></a>\n.+?<h3><a title="(.+?)" href=".+?">').findall(html)
	#results = re.compile('<img src="(.+?)" /></a>\n.+?<h3><a title="(.+?)" href="(.+?)">\n.+?\n.+?</a></h3>\n.+?<ul class="infos">\n.+?<li>(.+?)</li>').findall(html)
	results = re.compile('<img src="(.+?)" /></a>\n.+?<h3><a title="(.+?)" href="(.+?)">\n.+?\n.+?</a></h3>\n.+?<ul class="infos">\n.+?<li>(.+?)</li>').findall(html)

	#Classer et eliminer les doublons
	results = set(results)
	#results = sorted(results)


	
	
	episodes = mc.ListItems()
	# Verifier si il s'agit d'epidodes ou de "videos relies"
	if hasEpidodes(url):
		
		
		for thumb,name,url,episode in results:
			if len(thumb) > 0:
				item = mc.ListItem(mc.ListItem.MEDIA_UNKNOWN)
				item.SetLabel(name)
				item.SetPath(url)
				item.SetProperty('flag','episodes') #FLAG
				item.SetThumbnail(thumb)
				item.SetDescription(episode)
				episodes.append(item)
		
		#episodes = sorted(episodes)
	
	
	return episodes

	
def getVideos(url):
	videos = []
	
	#mc.ShowDialogOk('Debug!', url)

	sg = mc.Http()
	html = sg.Get(url)
	results = re.compile('<div id=".+?" class="(.+?)"></div>').findall(html)
	
	videos = mc.ListItems()
	for mp4 in results:
		#mc.ShowDialogOk('Debug!', mp4)
		return mp4
		#		item = mc.ListItem(mc.ListItem.MEDIA_UNKNOWN)
#		item.SetLabel(name)
#		item.SetPath(url)
#		item.SetProperty('flag','videos') #FLAG
#		videos.append(item)

	
	#return videos

def playVideo(url):
	#mc.ShowDialogOk('Debug!', 'Jouer la video')
	mc.LogDebug("URL VIDEO: " + url)
	##Pr�parer mon object pour le lire.
	objVideo = mc.ListItem(mc.ListItem.MEDIA_UNKNOWN)
	objVideo.SetLabel('Mon Video')
	objVideo.SetPath(url)
	#objVideo.
	
	mc.HideDialogWait()	
	mc.GetPlayer().Play(objVideo)


# V�rifier si c'est des �pidodes relatives � l'�mission
def hasEpidodes(url):

	sg = mc.Http()
	html = sg.Get(url)
	results = re.compile('<h2 title="autres \xc3\xa9pisodes">autres \xc3\xa9pisodes</h2>').findall(html)

	if len(results) > 0:
		return True
	else:
		return False

		
